#!/usr/local/bin/python
# -*- coding: utf-8 -*-

'''
    用户对象定义
'''

import logging, traceback
from tornado.escape import json_encode,json_decode
import time

import log
import util
from util import CountUserUtil,ConfigManager
import const
import mysqlHelper
#import user
from user import UserManager 

import code_define


logger = logging.getLogger(__name__)


class RoomAddTimeStruct:
    '''续杯信息结构'''
    def __init__(self):
        self.m_time_max = const.Config_BarAddTime()      
        self.reload()
    
    def reload(self):
        self.m_time_begin = time.time()
        self.m_time_remain = self.m_time_max    #多少秒后显示续杯面板
        self.m_addtime_state = 0                #0:未续杯  1:已续杯
        self.m_list_uid = []                    #续杯用户
        self.m_agree_boy = 0                    #男方续杯结果(0默认， 1不同意, 2:同意)
        self.m_agree_girl = 0                   #女方续杯结果(0默认， 1不同意, 2:同意)
        self.m_pay_type = ""                    #续杯支付类型 "gold", "money"
        
    def setUserID(self, *vals):
        del self.m_list_uid[0:]
        for uid in vals:
            self.m_list_uid.append(uid)
    
    def isNewUser(self, uid_a, uid_b):
        if uid_a in self.m_list_uid and uid_b in self.m_list_uid:
            return False
        return True 

    def setAddTimeState(self, state = 1):
        self.m_addtime_state = state

    def getAddTimeState(self):
        return self.m_addtime_state
        
    def isAddtime(self): #是否续杯
        return self.m_addtime_state == 1    #0:未续杯  1:已续杯
        
    def getRemainTime(self):#获取剩余时间
        return self.m_time_remain
    
    def countRemainTime(self):#计算并保存剩余时间
        self.m_time_remain = int(self.m_time_max - (time.time() - self.m_time_begin))
        if self.m_time_remain < 0:
            self.m_time_remain = 0

    def setAgree(self, tmpUser, agree):
        '''设置某人续杯结果'''
        if tmpUser:
            if tmpUser.getSex() == 1:
                self.m_agree_boy = agree
            else:
                self.m_agree_girl = agree
                
    def setPayType(self, payType):
        '''设置续杯支付类型'''
        self.m_pay_type = payType

    def getPayType(self):
        '''获取续杯支付类型'''
        return self.m_pay_type
        
    
    def isAllSelect(self):
        '''是否全部提交续杯选择'''
        return self.m_agree_boy != 0 and self.m_agree_girl != 0
			
    
    def isAllAgree(self):
        '''是否全部同意续杯'''
        bAllAgree = self.m_agree_boy == 2 and self.m_agree_girl == 2
        if bAllAgree == True:  #全部同意续杯, 则打续杯标记
            self.setAddTimeState()
        return bAllAgree
    
    def isBoyAgree(self):
        '''男士是否同意续杯'''
        return self.m_agree_boy == 2
 
#----------
class Room:
    '''约会房间''' 
    
    def __init__(self, room_id, send_ask_uid):
        self.m_room_id = room_id            #房间ID
        self.m_list_user = []               #房间用户列表
        self.m_scene = 0                    #房间场景
       
        #self.m_send_ask_uid = send_ask_uid #主动请求搭讪者uid
        self.m_pk_uid = 0                   #PK者uid
        
        #self.m_begin_time = time.time()     #开始时间
        #self.m_end_time = time.time()       #结束时间
        
        self.m_begin_time_pk = 0            #pk开始时间
        self.m_end_time_pk = 0              #pk结束时间
        
        self.m_state = 0                    #约会房间状态 0:普通约会  1:PK中   
        self.m_state_nobother = 0           #0: 默认, 1:使用了防打扰牌道具, 2:使用了隐形符
        
        self.m_timer_id_pk = 0              #PK定时器
        self.m_timer_id_addtime = 0         #续杯定时器
        self.m_timer_id_Wait_addtime = 0    #等待续杯结果定时器
        self.m_addtime_info = RoomAddTimeStruct() #续杯信息
        
        self.m_timer_pk_begin = time.time() #PK定时器开始时间

    def isAdmitPK(self):
        '''是否允许准入PK'''
        bAdmit = False
        tmpTime = self.getTimeInterval() #当前聊了多少秒
        time_1 = const.Config_BarPK_Admit_Time_1() #准入PK 可以进入时间   (time_1 < admitTime < time_2   
        time_2 = const.Config_BarPK_Admit_Time_2() #准入PK 可以进入时间    and
        time_3 = const.Config_BarPK_Admit_Time_3() #准入PK 可以进入时间    admitTime > time_3)
        if time_1 < tmpTime < time_2 or tmpTime > time_3:
            bAdmit = True
        return bAdmit
    
    def enter(self, tmpUserObj):
        '''用户进入'''
        if tmpUserObj: 
            uid = tmpUserObj.getUID()
            socket_id = tmpUserObj.getSocketID()
            log.print_debug(logger, "Room enter, room_id:[%s], RoomUsers:%s, socket_id:[%s], uid:[%s]" 
                            % (self.m_room_id, self.m_list_user, socket_id, uid))
            
            tmpUserObj.setCurrentPlace("bar_room")
            tmpUserObj.setUserBarStateDouble()          #用户的酒吧状态 1:约会中
            tmpUserObj.setRoomID(self.m_room_id)        #用户的房间ID
            
            util.inserList(self.m_list_user, uid)       #用户ID加入房间用户列表
            
            BarOrderManager.instance().delFromBarSingleList(tmpUserObj) #从管理器单身队列删除
            BarOrderManager.instance().delFromAutoList(tmpUserObj)      #从自动等待邂逅队列删除
    
    def enterPK(self, tmpUserObj):
        '''PK者进入约会房间'''
        if tmpUserObj:
            uid = tmpUserObj.getUID()
            socket_id = tmpUserObj.getSocketID()
            log.print_debug(logger, "Room enterPK, room_id:[%s], RoomUsers:%s, socket_id:[%s], uid:[%s]" 
                            % (self.m_room_id, self.m_list_user, socket_id, uid))
            tmpUserObj.setCurrentPlace("bar_room")
            tmpUserObj.setUserBarStatePK()              #用户的酒吧状态  2:PK中
            tmpUserObj.setRoomID(self.m_room_id)        #用户的房间ID
            
            util.inserList(self.m_list_user, uid)       #pk者ID加入房间用户列表

            self.m_pk_uid = uid
            self.m_begin_time_pk = time.time()    
            
            BarOrderManager.instance().delFromBarSingleList(tmpUserObj) #从管理器单身队列删除
            BarOrderManager.instance().delFromAutoList(tmpUserObj)      #从自动等待邂逅队列删除
           
    def killUser(self, tmpUserObj):
        '''从约会中退出(被踢出), 修改用户的状态信息'''
        if tmpUserObj:
            uid = tmpUserObj.getUID()
            socket_id = tmpUserObj.getSocketID()
            log.print_debug(logger, "Room killUser, room_id:[%s], RoomUsers:%s, socket_id:[%s], uid:[%s]" 
                            % (self.m_room_id, self.m_list_user, socket_id, uid))
            tmpUserObj.setCurrentPlace("bar")
            tmpUserObj.setUserBarStateSingle()          #用户的酒吧状态 0:单身            
            tmpUserObj.setRoomID(0)                     #用户的房间ID
            
            util.deleteFromList(self.m_list_user, uid)  #从房间用户列表删除
            
            #插入管理器单身队列
            BarOrderManager.instance().insertBarSingleList(tmpUserObj)
            
            
    #-----------房间场景--------
    def getRoomScene(self):
        return self.m_scene
    
    def setRoomScene(self, val):
        self.m_scene = val
            
            
    #---房间状态为-------------------
    def getRoomState(self):
        '''获取房间状态'''
        return self.m_state
    
    def setStateDefault(self):
        '''设置房间状态为PK状态中 普通约会'''
        if self.m_state == 1:
            self.m_end_time_pk = time.time()            
        self.m_state = 0     #房间状态 0:普通约会
    
    def setStatePK(self):
        '''设置房间状态为PK状态中 '''
        if self.m_state == 0:
            self.m_begin_time_pk = time.time()
        self.m_state = 1     #房间状态 1:PK    

    def isStatePK(self):
        '''房间状态是否是PK'''
        return self.m_state == 1
        
    #---房间免打搅状态--------------
    def getRoomStateNobother(self):
        '''获取房间免打搅状态'''
        return self.m_state_nobother
        
    def setStateNobother(self, val):
        self.m_state_nobother = val     #0: 默认, 1:使用了防打扰牌道具, 2:使用了隐形符
    
    def isStateNobother(self):
        '''是否不能打搅'''
        return self.m_state_nobother != 0     #1:使用了防打扰牌道具, 2:使用了隐形符
        
    #------------------ 
    def pushRoomUserBarState(self):
        '''给房间所有人push用户状态消息'''
        log.print_debug(logger, "Room pushRoomUserBarState, room_id:[%s], RoomUsers:%s" % (self.m_room_id, self.m_list_user))
        for uid in self.m_list_user:
            tmpUser = UserManager.get_user_by_uid(uid)
            if tmpUser:
                BarOrderManager.instance().pushUserBarState(tmpUser)  #发送用户A的状态变化通知在“看见我的用户列表"的所有人
                
    
    def sendMsgToAll(self, tmpCmd, tmpSendMsgUtil):
        '''给房间所有人发消息'''
        tmpMsg = tmpSendMsgUtil.getEncodeContent() #编码
        log.print_debug(logger, "Room sendMsgToAll, room_id:[%s], RoomUsers:%s, content:\ncmd:[%s], msg:%s" 
                        % (self.m_room_id, self.m_list_user, tmpCmd, tmpMsg))
        for uid in self.m_list_user:
            tmpUser = UserManager.get_user_by_uid(uid)
            if tmpUser:
                tmpSendMsgUtil.send(cmd=tmpCmd, request=tmpUser.m_request, msg=tmpMsg)        
    
    def sendMsgToAllExt(self, tmpCmd, tmpSendMsgUtil, *tmpUIDTuple):
        '''给房间除了tmpUIDTuple之外的人发消息'''
        tmpMsg = tmpSendMsgUtil.getEncodeContent() #编码     
        log.print_debug(logger, "Room sendMsgToAllExt, room_id:[%s], RoomUsers:%s, ExtUsers:%s, \ncmd:[%s], msg:%s" 
                        % (self.m_room_id, self.m_list_user, tmpUIDTuple, tmpCmd, tmpMsg))
        for uid in self.m_list_user:
            if uid in tmpUIDTuple:
                continue
            tmpUser = UserManager.get_user_by_uid(uid)
            if tmpUser:
                tmpSendMsgUtil.send(cmd=tmpCmd, request=tmpUser.m_request, msg=tmpMsg)
    
    def sendMsgToOne(self, tmpCmd, tmpSendMsgUtil, tmpUser):
        '''给房间某人发消息'''
        if tmpUser:   
            tmpMsg = tmpSendMsgUtil.getEncodeContent() #编码
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID()
            log.print_debug(logger, "Room sendMsgToOne, room_id:[%s], RoomUsers:%s, socket_id:[%s], uid:[%s]" 
                            % (self.m_room_id, self.m_list_user, socket_id, uid))
            tmpSendMsgUtil.send(cmd=tmpCmd, request=tmpUser.m_request, msg=tmpMsg)
    
    #---- 
    def getBeginTime(self):
        '''获取开始聊天时间'''
        return int(self.m_addtime_info.m_time_begin)
		
    def getTimeInterval(self):
        '''获取聊天运行时间'''
        return int(time.time() - self.getBeginTime())
    
    def getPKTimeInterval(self):
        '''获取PK运行时间'''
        return self.m_end_time_pk - self.m_begin_time_pk
    
    #----    
    def getRoomUserList(self):
        '''获取房间用户队列'''
        return self.m_list_user
    
    def getRoomUserObjList(self):
        '''获取房间所有人信息,返回队列'''
        tmpReturn = []
        for uid in self.m_list_user:
            tmpUser = UserManager.get_user_by_uid(uid)
            if tmpUser:
                tmpReturn.append(tmpUser)
        return tmpReturn
    
    def getRoomUserObjMapExt(self):
        '''获取房间所有人信息,返回字典(pk状态)'''
        tmpList = self.m_list_user[0:]              
        if len(tmpList) != 3:
            return None
        if self.m_pk_uid not in tmpList:
            return None
                
        tmpList.remove(self.m_pk_uid)
        tmpReturn = {}
        
        tmpUserPK = UserManager.get_user_by_uid(self.m_pk_uid)
        tmpUserA = UserManager.get_user_by_uid(tmpList[0])
        tmpUserB = UserManager.get_user_by_uid(tmpList[1])
        
        tmpReturn["pk"] = tmpUserPK
        if tmpUserPK.getSex() == tmpUserA.getSex():
            tmpReturn["other"] = tmpUserA   #性别跟PK相同, 则为原配
            tmpReturn["only"] = tmpUserB    #否则为裁判者
        else:
            tmpReturn["other"] = tmpUserB
            tmpReturn["only"] = tmpUserA
        return tmpReturn
 
    #----
    def getUser_PK(self):
        '''获取PK对象'''
        if self.m_state == 1:#约会房间状态 0:普通约会  1:PK中  2:免打搅
            return UserManager.get_user_by_uid(self.m_pk_uid)
        else:
            return None

    def getPKUID(self):
        '''获取PK对象'''
        if self.m_state == 1:#约会房间状态 0:普通约会  1:PK中  2:免打搅
            return self.m_pk_uid
        else:
            return 0
        
        
    #----
    def getUser_Only(self):
        '''(pk状态中使用)获取裁判对象'''
        if self.m_state == 1:#约会房间状态 0:普通约会  1:PK中  2:免打搅
            tmpPK = UserManager.get_user_by_uid(self.m_pk_uid)
            tmpA, tmpB, tmpC = self.getRoomUserObjList()
            if tmpA.getSex() != tmpPK.getSex():
                return tmpA
            if tmpB.getSex() != tmpPK.getSex():
                return tmpB
            if tmpC.getSex() != tmpPK.getSex():
                return tmpC
        return None
    
    #----
    def getUser_Other(self):
        '''(pk状态中使用)获取被PK对象'''
        if self.m_state == 1:#约会房间状态 0:普通约会  1:PK中  2:免打搅
            tmpPK = UserManager.get_user_by_uid(self.m_pk_uid)
            tmpA, tmpB, tmpC = self.getRoomUserObjList()
            if tmpA != tmpPK and tmpA.getSex() == tmpPK.getSex():
                return tmpA
            if tmpB != tmpPK and tmpB.getSex() == tmpPK.getSex():
                return tmpB
            if tmpC != tmpPK and tmpC.getSex() == tmpPK.getSex():
                return tmpC
        return None
 
    #----
    def getAnotherUser(self, tmpUser):
        '''获取另一个用户'''
        if not tmpUser:
            return None
        tmpA = None
        tmpB = None
        tmpUsers = self.getRoomUserObjList()
        
        if len(tmpUsers) == 2:      #普通约会状态
            tmpA, tmpB = tmpUsers
        elif len(tmpUsers) == 3:    #pk中
            tmpList = self.m_list_user[0:] 
            if self.m_pk_uid not in tmpList:
                return None
            tmpList.remove(self.m_pk_uid)            
            tmpA = UserManager.get_user_by_uid(tmpList[0])
            tmpB = UserManager.get_user_by_uid(tmpList[1])
        else:
            return None
        if tmpUser is tmpA:
            return tmpB
        elif tmpUser is tmpB:
            return tmpA
        else:
            return None
        
    #----
    def getPKUID(self):
        return self.m_pk_uid
    
    #----
    def getRoomID(self):
        return self.m_room_id
    
    #----
    def isUserInRoom(self, uid):
        return uid in self.m_list_user
    
    #----是否PK者
    def isUserIsPK(self, uid):
        return uid == self.m_pk_uid
    
    #---是否裁判(约会PK中)
    def isUserIsOnly(self, uid):
        tmpList = self.m_list_user[0:]              
        if len(tmpList) != 3:
            return None
        if self.m_pk_uid not in tmpList:
            return None
                
        tmpList.remove(self.m_pk_uid)
        tmpUserPK = UserManager.get_user_by_uid(self.m_pk_uid)
        tmpUserA = UserManager.get_user_by_uid(tmpList[0])
        tmpUserB = UserManager.get_user_by_uid(tmpList[1])
        
        tmpUserOnly = None
        if tmpUserPK.getSex() == tmpUserA.getSex():
            tmpUserOnly = tmpUserB    #否则为裁判者
        else:
            tmpUserOnly = tmpUserA    #否则为裁判者

        return tmpUserOnly.getUID() == uid
    
    def getTalkingUserType(self, tmpUser): 
        '''获取聊天者类型(pk, only, other)'''
        if not tmpUser:
            return ""
        
        uid = tmpUser.getUID()
        if uid == self.m_pk_uid:
            return "pk"
        
        bOnly = self.isUserIsOnly(uid)
        if bOnly is None:
            return ""
        if bOnly:
            return "only"
        elif bOnly == False:
            return "other" 
        
#---wudi
    @staticmethod
    def getPKResult(aInfo, bInfo, online=0):    #aInfo 为发起攻击者
        '''读取PK 配置信息'''
        tizhibeishu = const.Config_PK_Constitution_Multiple()  #体质倍数
        levelbeishu = const.Config_PK_Level_Multiple()  #人物等级倍数
        shanbilvbfb = float(const.Config_PK_Shanbi_Baifenbi())/100  #闪避率百分比
        yangmaobfb = float(const.Config_PK_Appearance_Baifenbi())/1000  #样貌点数百分比
        baojilvbfb = float(const.Config_PK_Baoji_Baifenbi())/100  #暴击率百分比
        qingxiubfb = float(const.Config_PK_Mood_Baifenbi())/1000  #情绪点数百分比
        baojirandas = const.Config_PK_Baoji_Rand_A_start()  #暴击随机数A范围开始值
        baojirandae = const.Config_PK_Baoji_Rand_A_end()  #暴击随机数A范围结束值
        baojirandbs = const.Config_PK_Baoji_Rand_B_start()  #暴击随机数B范围开始值
        baojirandbe = const.Config_PK_Baoji_Rand_B_end()  #暴击随机数B范围结束值
        fangyuxishu = float(const.Config_PK_FangYuXiShu())/1000  #防御系数
        gongjixishu = const.Config_PK_GongJiXiShu()  #攻击系数
        print "@wudi@>PK>var>",tizhibeishu,levelbeishu,shanbilvbfb,yangmaobfb,baojilvbfb,qingxiubfb,baojirandas,baojirandae,baojirandbs,baojirandbe,fangyuxishu,gongjixishu
        '''比较PK者和被PK者的胜负,A为在线用户，B可能为数据库查询的数据'''
        #设置PK要用到的用户信息
        tmpA = UserManager.get_user_by_uid(aInfo)
        userA = {
             "uid" : tmpA.getUID(),  #用户ID
             "nickname" : tmpA.getNickname(),
             "eloquence" : tmpA.getEloquence(), #口才
             "knowledge" : tmpA.getKnowledge(),  #知识
             "constitution" : tmpA.getConstitution(),   #体质
             "mood" : tmpA.getMood(),  #情绪
             "appearance" : tmpA.getAppearance(), #样貌
             "level" : tmpA.getLevel() #等级
             }
        userA["shengming"] = userA["constitution"]*tizhibeishu + userA["level"]*levelbeishu

        if online==1:
            tmpB = UserManager.get_user_by_uid(bInfo)
            userB = {
                 "uid" : tmpB.getUID(),  #用户ID
                 "nickname" : tmpB.getNickname(),
                 "eloquence" : tmpB.getEloquence(), #口才
                 "knowledge" : tmpB.getKnowledge(),  #知识
                 "constitution" : tmpB.getConstitution(),   #体质
                 "mood" : tmpB.getMood(),  #情绪
                 "appearance" : tmpB.getAppearance(), #样貌
                 "level" : tmpB.getLevel() #等级
                 }
            userB["shengming"] = userB["constitution"]*tizhibeishu + userB["level"]*levelbeishu
        else:
            tmpB = UserManager.get_user_game_info(bInfo)
            userB = {
                 "uid" : tmpB['uid'],  #用户ID
                 "nickname" : tmpB['nickname'],
                 "eloquence" : tmpB['eloquence'], #口才
                 "knowledge" : tmpB['knowledge'],  #知识
                 "constitution" : tmpB['constitution'],   #体质
                 "mood" : tmpB['mood'],  #情绪
                 "appearance" : tmpB['appearance'], #样貌
                 "level" : tmpB['level'] #等级
                 }
            userB["shengming"] = userB["constitution"]*tizhibeishu + userB["level"]*levelbeishu

        if not tmpA or not tmpB:
            return False

        print "@@@@@www>初始值>>", userA, userB

        numHuiHe = 0    #回合数
        warResultList = []  #保存每次攻击结果
        huiheResult = {}       #记录回合结果
        
        #判断谁先发起攻击
        if userA["knowledge"] >= userB["knowledge"]:
            firsterWar = userA
            toUser = userB
            print "@@@@@>if>先发起攻击者>", firsterWar
            print "@@@@@>if>受击者>", toUser
        else:
            firsterWar = userB
            toUser = userA
            print "@@@@@>if else>先发起攻击者>", firsterWar
            print "@@@@@>if else>受击者>", toUser

        conn = mysqlHelper.mysql()
        sql = "SELECT * from t_pk_msg where msgtype='mainhtml' limit 1"     #文字最外面的html格式
        mainhtml = conn.getRow(sql)
        print "@@@>", mainhtml

        sql = "SELECT * from t_pk_msg where msgtype='nickname' limit 1"     #昵称格式
        nickname_msg = conn.getRow(sql)
        print "@@@>", nickname_msg

        sql = "SELECT * from t_pk_msg where msgtype='nickname2' limit 1"     #昵称格式
        nickname2_msg = conn.getRow(sql)
        print "@@@>", nickname2_msg

        sql = "SELECT * from t_pk_msg where msgtype='shanghai_msg_start' limit 1"       #伤害修饰语-开始
        shanghai_msg_start = conn.getRow(sql)
        print "@@@>", shanghai_msg_start

        sql = "SELECT * from t_pk_msg where msgtype='shanghainum' limit 1"       #伤害数值
        shanghainum = conn.getRow(sql)
        print "@@@>", shanghainum

        sql = "SELECT * from t_pk_msg where msgtype='shanghai_msg_end' limit 1"       #伤害修饰语-结束
        shanghai_msg_end = conn.getRow(sql)
        print "@@@>", shanghai_msg_end
        
        
        #开始攻击
        while 1:
            huiheResult = {}
            sql = "SELECT * from t_pk_msg where msgtype='xiushi' order by rand() limit 1"       #修饰语
            xiushi_msg = conn.getRow(sql)
            print "@@@>", xiushi_msg

            if util.rander(int((shanbilvbfb+firsterWar["appearance"]*yangmaobfb)*100)):   #闪避率    0:闪避成功    1:闪避失败
                shanbi = 0
                sql = "SELECT * from t_pk_msg where msgtype='shanbi' order by rand() limit 1"       #暴击格式
                shanbi_msg = conn.getRow(sql)
                print "@@@>", shanbi_msg
                shanbi_msg_html = shanbi_msg['html_start'] + shanbi_msg['msg'] + shanbi_msg['html_end']
            else:
                shanbi = 1
                shanbi_msg_html = ''
        
            if util.rander(int((baojilvbfb+firsterWar["mood"]*qingxiubfb)*100)):  #暴击率
                baoji = 1
                sql = "SELECT * from t_pk_msg where msgtype='baoji' order by rand() limit 1"       #暴击格式
                baoji_msg = conn.getRow(sql)
                baoji_msg_html = baoji_msg['html_start'] + baoji_msg['msg'] + baoji_msg['html_end']
                print "@@@>", baoji_msg
            else:
                baoji = 0
                baoji_msg_html = ''
        
            killNum = firsterWar["eloquence"] * (util.randomRandInt(baojirandas,baojirandae)*0.1 + (util.randomRandInt(baojirandbs,baojirandbe)*0.1)*baoji) * (1-firsterWar["eloquence"]*fangyuxishu) * gongjixishu * shanbi
            killNum = int(killNum)

            print "@@@@@www>伤害值>", killNum
            print "@@@@@www>攻击者当前生命值>", firsterWar['shengming']
            print "@@@@@www>受击者当前生命值>", toUser['shengming']

            toUser["shengming"] -= killNum  #更新受击者生命值
            print "@@@@@www>受击者本回合剩余生命值>", toUser['shengming']
            if int(toUser["shengming"])<=0:
                toUser["shengming"] = 0

            huiheResult['firstshengming'] = firsterWar['shengming']
            huiheResult['toUsershengming'] = toUser['shengming']

            huiheMsg = nickname_msg['html_start'] + firsterWar['nickname'] + nickname_msg['html_end']
            huiheMsg += xiushi_msg['html_start'] + xiushi_msg['msg'] + xiushi_msg['html_end']
            huiheMsg += baoji_msg_html
            huiheMsg += nickname2_msg['html_start'] + toUser['nickname'] + nickname2_msg['html_end']
            huiheMsg += shanbi_msg_html
            huiheMsg += shanghai_msg_start['html_start'] + shanghai_msg_start['msg'] + shanghai_msg_start['html_end']
            huiheMsg += shanghainum['html_start'] + str(killNum) + shanghainum['html_end']
            huiheMsg += shanghai_msg_end['html_start'] + shanghai_msg_end['msg'] + shanghai_msg_end['html_end']
            huiheMsg = mainhtml['html_start'] + huiheMsg + mainhtml['html_end']
            huiheResult['huihemsg'] = huiheMsg

            numHuiHe += 1
            huiheResult['huihehnum'] = numHuiHe
            huiheResult['baoji'] = baoji
            huiheResult['shanbi'] = shanbi
            huiheResult['killNum'] = killNum
            huiheResult['firstUID'] = firsterWar['uid']
            huiheResult['toUID'] = toUser['uid']

            if toUser["shengming"]<=0:  #生命值小于0，PK结束
                huiheResult['winUID'] = firsterWar['uid']
                warResultList.append(huiheResult)
                print "@@@@@>if>>>", huiheResult
                break
            else:
                print "@@@@@>else>>>", huiheResult
                #受击方生命值大于0，继续PK，换对方攻击
                tmpUser = firsterWar
                firsterWar = toUser
                toUser = tmpUser
            
            warResultList.append(huiheResult)
        #print '@@@www>', warResultList
        return warResultList
    
    #----开启pk定时器
    def startTimerPK(self, func, *parms):
        self.stopTimerPK()
        self.m_timer_pk_begin = time.time()         #PK定时器开始时间
        mstime = const.Config_BarPKLimitTime()      #酒吧约会房间 PK时间 限制 60秒
        self.m_timer_id_pk = util.TimerManager.instance().add_timer(func, mstime, 1, parms)         
        log.print_debug(logger, "Room startTimerPK, room_id:[%s], RoomUsers:%s, timer_id:[%s] " 
                        % (self.m_room_id, self.m_list_user, self.m_timer_id_pk))
    
    #----关闭PK定时器
    def stopTimerPK(self):
        if self.m_timer_id_pk > 0:
            log.print_debug(logger, "Room stopTimerPK, room_id:[%s], RoomUsers:%s, timer_id:[%s] " 
                        % (self.m_room_id, self.m_list_user, self.m_timer_id_pk))
            util.TimerManager.instance().delete(self.m_timer_id_pk)
            self.m_timer_id_pk = 0
            
    def getTimerPKLimitTime(self):
        '''获取PK定时器剩余时间'''
        tmpPKTimeDefault = const.Config_BarPKLimitTime()    #酒吧约会房间 PK时间(默认限制 60秒)
        tmpPKTime = int(time.time() - self.m_timer_pk_begin)#已倒计的时间 
        return int(tmpPKTimeDefault - tmpPKTime)
            
    #----开启续杯定时器
    def startTimerAddTime(self, func, bNew=True, *parms):
        '''参数:(self, 处理func, 是否第一次开启, 用户A, 用户B, room对象)'''
        self.stopTimerAddTime() 
        
        if bNew:
            self.m_addtime_info.reload()
        self.m_addtime_info.setUserID(parms[0].getUID(), parms[1].getUID())     #保存当前聊天者ID

        mstime = self.m_addtime_info.getRemainTime()    #多少秒后显示续杯面板
        self.m_timer_id_addtime = util.TimerManager.instance().add_timer(func, mstime, 1, parms)    
        log.print_debug(logger, "Room startTimerAddTime, room_id:[%s], RoomUsers:%s, timer_id:[%s], RemainTime:[%s]" 
                        % (self.m_room_id, self.m_list_user, self.m_timer_id_addtime, mstime))
    #----关闭续杯定时器
    def stopTimerAddTime(self):
        if self.m_timer_id_addtime > 0:
            log.print_debug(logger, "Room stopTimerAddTime, room_id:[%s], RoomUsers:%s, timer_id:[%s] " 
                        % (self.m_room_id, self.m_list_user, self.m_timer_id_addtime))
            util.TimerManager.instance().delete(self.m_timer_id_addtime)       
            self.m_timer_id_addtime = 0
            self.m_addtime_info.countRemainTime() #续杯信息-计算并保存剩余时间

    #----开启等待续杯结果定时器
    def startTimerWaitAddTime(self, func, *parms):
        self.stopTimerWaitAddTime()
        mstime = const.Config_BarWaitAddTime()   #酒吧约会房间 等待续杯结果时间
        self.m_timer_id_Wait_addtime = util.TimerManager.instance().add_timer(func, mstime, 1, parms)
        log.print_debug(logger, "Room startTimerWaitAddTime, room_id:[%s], RoomUsers:%s, timer_id:[%s] " 
                        % (self.m_room_id, self.m_list_user, self.m_timer_id_Wait_addtime))
        
    #----关闭等待续杯结果定时器
    def stopTimerWaitAddTime(self):
        if self.m_timer_id_Wait_addtime > 0:
            log.print_debug(logger, "Room stopTimerWaitAddTime, room_id:[%s], RoomUsers:%s, timer_id:[%s] " 
                        % (self.m_room_id, self.m_list_user, self.m_timer_id_Wait_addtime))
            util.TimerManager.instance().delete(self.m_timer_id_Wait_addtime)
            self.m_timer_id_Wait_addtime = 0
            
    def stopAllTimer(self):
        '''关闭所有定时器'''
        log.print_debug(logger, "Room stopAllTimer, room_id:[%s], RoomUsers:%s " 
                        % (self.m_room_id, self.m_list_user))
        self.stopTimerPK()          #-关闭PK定时器
        self.stopTimerAddTime()     #-关闭续杯定时器
        self.stopTimerWaitAddTime() #-关闭等待续杯结果定时器
        
    def getExpByTalkTime(self):
        '''根据聊天时间获取经验值''' 
        tmpConfigSecond = const.Config_Bar_end_not_exp_time()   #邂逅结束--多少秒经验每分钟按步长递增(秒)
        tmpStepExp = const.Config_Bar_end_exp_step()            #邂逅结束--多少秒内每分钟获得的经验步长
        tmpTimeSecond = self.getTimeInterval()  #秒
        tmpTimeMinute = int(tmpTimeSecond / 60) #分钟
        tmpRes = 0

        if tmpTimeSecond <= tmpConfigSecond:      #多少秒经验每分钟按步长递增
            tmpRes = int(tmpTimeMinute * tmpStepExp)
        elif tmpTimeMinute < 10:    #少于10分钟都是10经验
            tmpRes = 10
        else:
            import math
            tmpRes = int((math.log(tmpTimeMinute/5, 2) + 1) * 10)
            if tmpRes > 100:    #获得的经验值最大100
                tmpRes = 100
                
        log.print_debug(logger, "Room getExpByTalkTime, room_id:[%s], RoomUsers:%s, timeSecond[%s], timeMinute[%s], resExp[%s]" 
                        % (self.m_room_id, self.m_list_user, tmpTimeSecond, tmpTimeMinute, tmpRes))
        return tmpRes
    
    def getGoldByTalkTime(self):
        '''根据聊天时间获得翻牌金币''' 
        tmpConfigBegin_boy = const.Config_BarGoldRandBegin()            #酒吧约会房间随机金币范围-男
        tmpConfigEnd_boy = const.Config_BarGoldRandEnd()                #酒吧约会房间随机金币范围-男
        tmpConfigBegin_girl = const.Config_BarGoldRandBegin_girl()      #酒吧约会房间随机金币范围-女
        tmpConfigEnd_girl = const.Config_BarGoldRandEnd_girl()          #酒吧约会房间随机金币范围-女   
        tmpConfigRandGold_step = const.Config_BarGoldRand_step()        #酒吧约会房间随机金币-以5金币为变化单位
        
        tmpConfig_BarGoldRand_time = const.Config_BarGoldRand_time()          #酒吧约会房间多少秒内金币为以下范围 
        tmpConfig_BarGoldRandBegin_time = const.Config_BarGoldRandBegin_time()#酒吧约会房间多少秒内金币为范围 
        tmpConfig_BarGoldRandEnd_time = const.Config_BarGoldRandEnd_time()    #酒吧约会房间多少秒内金币为范围  

        tmpTimeSecond = self.getTimeInterval()  #秒
        tmpResGold_girl = 0
        tmpResGold_boy = 0
        import random
           
        if tmpTimeSecond < tmpConfig_BarGoldRand_time:      #少于秒数则按时间范围获取翻牌金币
            tmpResGold_girl = random.randint(tmpConfig_BarGoldRandBegin_time, tmpConfig_BarGoldRandEnd_time)
            tmpResGold_boy = random.randint(tmpConfig_BarGoldRandBegin_time, tmpConfig_BarGoldRandEnd_time)
        else:
            tmpResGold_girl = random.randint(tmpConfigBegin_girl, tmpConfigEnd_girl)
            tmpResGold_boy = random.randint(tmpConfigBegin_boy, tmpConfigEnd_boy)
            tmpResGold_girl = int(tmpResGold_girl/tmpConfigRandGold_step)*tmpConfigRandGold_step
            tmpResGold_boy = int(tmpResGold_boy/tmpConfigRandGold_step)*tmpConfigRandGold_step
                
        log.print_debug(logger, "Room getGoldByTalkTime, room_id:[%s], RoomUsers:%s, timeSecond[%s], resGold_girl[%s], resGold_boy[%s]" 
                        % (self.m_room_id, self.m_list_user, tmpTimeSecond, tmpResGold_girl, tmpResGold_boy))
        return [tmpResGold_girl, tmpResGold_boy]
   
#----------
class BarOrderManager(util.SingleClass):
    '''酒吧、名人堂管理器'''

    #--------
    s_map_user = {}			   #酒吧/名人堂-所有人 {"socket_id": userObj}
    
    s_map_user_by_province_single_boy = {}     #酒吧-单身男 {"省":[uid]}
    s_map_user_by_province_single_girl = {}    #酒吧-单身女 {"省":[uid]} 
   
    s_list_bar_single_boy = []  #酒吧-单身男 UID
    s_list_bar_single_girl = [] #酒吧-单身女 UID    
    
    s_list_bar_auto_boy = []   #酒吧-随机邂逅等待列表 男  UID
    s_list_bar_auto_girl = []  #酒吧-随机邂逅等待列表 女 UID
    s_map_user_by_province_auto_boy = {}     #酒吧-单身邂逅等待列表男 {"省":[uid]}
    s_map_user_by_province_auto_girl = {}    #酒吧-单身邂逅等待列表女 {"省":[uid]} 
    
    s_list_bar_T_boy = []      #酒吧-T台排队列表 男 UID
    s_list_bar_T_girl = []     #酒吧-T台排队列表 女 UID 
    s_bar_T_boy_current_uid = 0 #当前-T台排队列表 男
    s_bar_T_girl_current_uid = 0#当前-T台排队列表 女
    
    #----约会房间----
    s_room_index = 0            #酒吧-房间自增序号
    s_map_bar_room = {}         #酒吧-约会房间列表 {"room_id": room}
    
    #----名人堂---
    s_map_order_boy = {}                #名人堂-排名列表 男 {uid:排名}
    s_map_order_boy_by_order = {}       #名人堂-排名列表 男 #{排名: {type, uid}}
    
    s_map_order_girl = {}               #名人堂-排名列表 女 {uid:排名}
    s_map_order_girl_by_order = {}      #名人堂-排名列表 女 #{排名: {type, uid}}
    
    s_list_bar_king_boy = []      #酒吧-后冠排队列表 男 UID
    s_list_bar_king_girl = []     #酒吧-后冠排队列表 女 UID
    
    s_king_count_boy = 0
    s_king_count_girl = 0
    
    #-----定时器---
    s_timer_id_sort = 0             #排序定时器ID
    s_timer_id_t_list = 0           #T台队列定时器

    #----
    def __init__(self):
        pass

    #----
    def enter(self, tmpUser, place="bar"): 
        if tmpUser:            
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID()
            log.print_debug(logger, "BarOrderManager enter, socket_id:[%s], uid:[%s]" % (socket_id, uid))
            
            BarOrderManager.s_map_user[socket_id] = tmpUser #保存到酒吧用户map
            self.insertBarSingleList(tmpUser) #插入单身队列
            
            tmpUser.setCurrentPlace(place) #所在模块
            tmpUser.setUserBarStateSingle()#酒吧状态0:单身
                        
            #--判断该用户后冠是否有效, 有效则插入后冠队列
            from props_manager import PropManager
            tmpProps = PropManager.instance().isUsingPropKing(tmpUser)
            if tmpProps:                    
                self.insertKingList(tmpUser)
        
    #----
    def _leave(self, tmpUser):
        if tmpUser:
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID() 
            log.print_debug(logger, "BarOrderManager leave, socket_id:[%s], uid:[%s]" % (socket_id, uid))
                                  
            if BarOrderManager.s_map_user.has_key(socket_id):
                BarOrderManager.s_map_user.pop(socket_id) #从酒吧用户map删除
                
            self.delFromBarSingleList(tmpUser)  #从单身队列删除           
            self.delFromAutoList(tmpUser)       #从自动等待邂逅队列删除
            
            tmpUser.setUserBarStateExit()       #用户酒吧状态为-1 ,离开
        
    #---获取男或女单身数量- 
    def getSingleCount(self, sex):
        if sex == 1:
            return len(BarOrderManager.s_list_bar_single_boy) #酒吧-单身男 UID
        else:
            return len(BarOrderManager.s_list_bar_single_girl) #酒吧-单身女 UID 
    
    #---获取总单身数量- 
    def getTotalSingleCount(self):
        tmpCount = len(BarOrderManager.s_list_bar_single_boy)
        tmpCount += len(BarOrderManager.s_list_bar_single_girl)
        return tmpCount

    #---获取约会中房间数量- 
    def getTotalDoubleCount(self):
        return len(BarOrderManager.s_map_bar_room)
            
    #----
    def getUser(self, socket_id):
        return BarOrderManager.s_map_user.get(socket_id)

    def getBarRoomRandGiftGoodsList(self, tmpUser):
        '''根据规则返回翻牌获取的随机掉落礼品包'''
        tmpResult = ([], 0, 0)
        if not tmpUser:
            return tmpResult
        
        tmpLevel = tmpUser.getLevel()
        tmpGoodsList = []
        tmpGiftLevel = 0
        tmpBoolGetLevelGift = 0 #当前获得的是否等级礼包, 0为非， 1为获得
        
        import random
        bRole_1 = eval(const.Config_props_levelgift_str_role_1) #"(tmpLevel-8) % 10 == 0"      #规则1: (10*N + 8) == tmpLevel
        bRole_2 = True
        if const.Config_props_levelgift_debug_open_random == 1:  # 1:开启几率; 0:不开启几率
            bRole_2 = eval(const.Config_props_levelgift_str_role_2) #" random.randint(1, 10) == 1" #规则2: 有几率获取礼包
        if bRole_1 and bRole_2: 
            tmpGiftLevel = eval(const.Config_props_levelgift_str_role_gift) # " 10*(tmpLevel-8)/10+1) "  #等级礼包 的等级
            tmpGoodsList = util.ConfigManager.getGiftGoodsListByLevel(tmpGiftLevel) #获取等级对应的礼包信息 
            if tmpUser.isGetGiftGoods(tmpGiftLevel):  #如果已经获取过该等级的等级礼包, 则不能再次获取 
                tmpGoodsList = []
                tmpBoolGetLevelGift = 1  #当前获得的是否等级礼包, 0为非， 1为获得
            tmpResult = (tmpGoodsList, tmpGiftLevel, tmpBoolGetLevelGift)
            
        if tmpResult[2] == 0:  #表示没有等级礼品, 则从配置里根据概率送普通商品
            tmpRandom = random.randint(1, 100)
            tmpConfigGiftDict = const.Config_BarFinish_giftAndRandomDict()
            tmpI = 1
            for k, v in tmpConfigGiftDict.items():
                tmpRangeList = range(tmpI, v+tmpI)
                tmpI = v + tmpI
                if tmpRandom in tmpRangeList:   #随机数 在 概率范围
                    tmpGiftGoodsID = int(k)
                    tmpGoodsList = [tmpGiftGoodsID]
                    break
            tmpResult = (tmpGoodsList, tmpGiftLevel, tmpBoolGetLevelGift)
            
        return tmpResult
    
    #----
    def getUserInfoToClient(self, tmpUser):
        '''获取客户端需要的用户信息, 返回字典, 可以加入发送器'''
        if not tmpUser:
            return {}
        tmpUser.setUserInfoPropMagic();  #从在使用的道具更新 magic卡
        tmpMap = util.getSomeItemFromDict(tmpUser.m_userinfo, 
               "uid", "sex", "nickname", "blood", "income", "edu", "birthday", 
               "age", "height", "province", "city", "country", "otherarea", "reg_step",                   
               "level", "exp", "charm", "assets", "gold", "money", "energy", 
               "eloquence", "knowledge", "constitution", "mood", "appearance",
               "my_bodyinfo", "my_props_using", "magic", "last_login_time", "cloth_charm", "count_room","count_invite", "count_pk_success")
        tmpMap["my_props_privilege"] = tmpUser.getUserInfoPropPrivilege()   #获取 正在使用的特权道具信息(如胸花)
        
        iLevel = tmpUser.getLevel()   
        tmpMap["level_exp"] = ConfigManager.getExpByLevel(iLevel)           #达到当前等级的最低经验值                     
        tmpMap["next_exp"] = ConfigManager.getExpByLevel(iLevel+1)          #达到下一等级的最低经验值
        
        tmpMap["energy"] = tmpUser.getEnergy()                              #当前'精力(人缘)' 
        tmpMap["max_energy"] = tmpUser.getCurrentMaxEnergy()                #当前的最大'精力(人缘)'[剩余人缘+我的关注人数量], 

        tmpMap["next_courage"] = ConfigManager.getCourageByLevel(iLevel+1)  #下一个等级的勇气
        tmpMap["next_quality"] = ConfigManager.getQualityByLevel(iLevel+1)  #下一个等级的人品
        tmpMap["next_energy"] = ConfigManager.getEnergyByLevel(iLevel+1)    #下一个等级的'精力(人缘)',            
        
        tmpMap["max_courage"] = ConfigManager.getCourageByLevel(iLevel)     #该等级最大的勇气值
        tmpMap["max_quality"] = ConfigManager.getQualityByLevel(iLevel)     #该等级最大的人品值
        
        tmpMap["max_power"] = const.Config_MaxPower() #最大体力值
        
        tmpMap["courage"] = util.CountUserUtil.getCurrentCourage(tmpUser)     #计算当前勇气值
        tmpMap["power"] = util.CountUserUtil.getCurrentPower(tmpUser)         #计算当前体力值
        tmpMap["quality"] = util.CountUserUtil.getCurrentQuality(tmpUser)     #计算当前人品值
        
        tmpMap["my_friend_size"] = tmpUser.getMyFriendListSize()            #我的好友数量
        
        return tmpMap
    
    #----
    def getUserInfoToClientForHallOfFame(self, tmpUser, parmsOrder=0):
        '''获取客户端需要的用户信息, 返回字典, 可以加入发送器,(名人堂使用)'''
        if not tmpUser:
            return {}
        tmpMap = self.getUserInfoToClient(tmpUser)
        
        tmpMap["my_friend_size"] = tmpUser.getMyAtttListSize()  #getMyFriendListSize()  #我的好友数量 //修改为我的关注数量
        tmpMap["hidden_love_me_size"] = tmpUser.getHiddenLoveMeListSize()   #粉丝数//暗恋我的数量
        tmpMap["order"] = parmsOrder    #排名
        
        tmpMap["friend_type"] = "default"  #类型, “default”:陌生人  “my_attt” 我关注的,  “attt_me”:关注我的, 
                                            # “my_hidden_love”: 我暗恋的,  ”hidden_love_me”: 暗恋我的
        return tmpMap
        
    def _tmpCreateStructCountCharm(self, tmpMap, tmpUser, itemName, tmpUnit, tmpAddVal):
        tmpDict = {}
        tmpDict["count"] = tmpUser.getUserInfoToInt(itemName)   #数量
        tmpDict["charm_unit"] = tmpUnit                         #单位
        tmpDict["charm_step"] = tmpAddVal                       #每单位数量 加多少魅力
        
        tmpMap[itemName] = tmpDict
        
    def getUserInfoToClientForLogin(self, tmpUser): 
        if not tmpUser:
            return {}
        tmpMap = self.getUserInfoToClient(tmpUser)
        
        tmpUnit = 1
        tmpAddVal = const.Config_presen_get_charm() #被对方送礼物1件, 魅力增减  
        self._tmpCreateStructCountCharm(tmpMap, tmpUser, "count_get_present", tmpUnit, tmpAddVal)  #收到的礼物次数
        
        tmpUnit = const.Config_Attention_get_charm_limit()   # 被关注10次加一次魅力值
        tmpAddVal = 1
        self._tmpCreateStructCountCharm(tmpMap, tmpUser, "count_atted", tmpUnit, tmpAddVal) # '被关注次数',
 
        tmpUnit = const.Config_visited_get_charm_limit() # 被拜访10次加一次魅力值
        tmpAddVal = 1
        self._tmpCreateStructCountCharm(tmpMap, tmpUser, "count_visited", tmpUnit, tmpAddVal) # '被拜访次数',
         
        tmpUnit = const.Config_left_mgs_get_limit()   # 被留言10次加一次魅力值
        tmpAddVal = 1
        self._tmpCreateStructCountCharm(tmpMap, tmpUser, "count_leftmsg", tmpUnit, tmpAddVal) # '被留言次数',
        
        tmpUnit = const.Config_roomer_get_charm_by_clean() #房主被打扫多少次加一点魅力 
        tmpAddVal = 1
        self._tmpCreateStructCountCharm(tmpMap, tmpUser, "count_cleaned", tmpUnit, tmpAddVal) # '被打扫次数',
        
        tmpUnit = const.Config_left_personnel_mgs_get_limit()   # 被私信5次增加魅力一点 
        tmpAddVal = 1
        self._tmpCreateStructCountCharm(tmpMap, tmpUser, "count_private_letter", tmpUnit, tmpAddVal) # '被私信次数'
         
        tmpUnit = const.Config_impressioned_get_charm_limit()  #被好友印象多少次,魅力增减一点
        tmpAddVal = 1
        self._tmpCreateStructCountCharm(tmpMap, tmpUser, "count_commented", tmpUnit, tmpAddVal) # '被评论次数', 
    
        return tmpMap
    
    #----
    def getUserInfoToClientExt(self, tmpUser):
        '''获取客户端需要的用户信息, 返回字典, 可以加入发送器'''
        tmpMap = self.getUserInfoToClient(tmpUser)
        util.deleteFromDict(tmpMap, "my_bodyinfo")      #删除某字段
        util.deleteFromDict(tmpMap, "my_props_using")   #删除某字段
        return tmpMap
        
    #----
    def getUserInfoToClientSimple(self, tmpUser):
        '''获取客户端需要的用户信息, 返回字典, 可以加入发送器'''
        if tmpUser:
            tmpUser.setUserInfoPropMagic();  #从在使用的道具更新 magic卡
            tmpMap = util.getSomeItemFromDict(tmpUser.m_userinfo, 
                   "uid", "sex", "nickname", "blood", "income", "edu", "birthday", 
                   "age", "height", "province", "city", "country", "otherarea",                    
                   "level", "exp", "charm", "cloth_charm", "magic")
            tmpMap["my_props_privilege"] = tmpUser.getUserInfoPropPrivilege()   #获取 正在使用的特权道具信息(如胸花)
            return tmpMap
        else:
            return {}
                
    #----
    def getUserInfoToClientSimpleExt(self, tmpUser):
        '''获取客户端需要的用户信息, 返回字典, 可以加入发送器'''
        if tmpUser:
            tmpMap = util.getSomeItemFromDict(tmpUser.m_userinfo, 
                   "uid", "sex", "nickname", "age", "level")
            return tmpMap
        else:
            return {} 
    
    
    #----T台队列-------------------------------------------
    def get_T_size(self, tmpUser): 
        '''获取异性T台排队数量'''
        sex = tmpUser.getSex()
        tmpList = BarOrderManager.s_list_bar_T_boy
        if sex == 1:
            tmpList = BarOrderManager.s_list_bar_T_girl
        return len(tmpList)
    
    #----
    def get_T_user_order(self, tmpUser): 
        '''获取用户在T台列表排名'''
        await = 0  
        if tmpUser:
            sex = tmpUser.getSex()
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID()
    
            tmpList = BarOrderManager.s_list_bar_T_boy
            if sex == 0:
                tmpList = BarOrderManager.s_list_bar_T_girl
            if uid in tmpList:
                await = tmpList.index(uid) + 1
            log.print_debug(logger, "get_T_user_order exec, socket_id:[%s], uid:[%s], await:[%s]" % (socket_id, uid, await))      
        return await
    
    #----插入T台队列
    def insertTUserList(self, tmpUser):
        if tmpUser:
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID()
                
            tmpList = BarOrderManager.s_list_bar_T_girl
            if tmpUser.getSex() == 1: #性别(0女 1男)
                tmpList = BarOrderManager.s_list_bar_T_boy
            util.inserList(tmpList, uid)
            
            tmpUser.addUserInfoPropPrivilegeBrooch() #增加 T台胸花到 "正在使用的的特权道具列表"
            
            log.print_debug(logger, "BarOrderManager insertTUserList exec, socket_id:[%s], uid:[%s], \nlist:%s" % (socket_id,uid, tmpList))
    
    #---从T台队列删除
    def delFromBTUserList(self, tmpUser):
        if tmpUser:
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID()

            tmpList = BarOrderManager.s_list_bar_T_girl
            if tmpUser.getSex() == 1:#性别(0女 1男)
                tmpList = BarOrderManager.s_list_bar_T_boy            
            util.deleteFromList(tmpList, uid) 
            
            tmpUser.delUserInfoPropPrivilegeBrooch() #删除 T台胸花到 "正在使用的的特权道具列表"
            
            log.print_debug(logger, "BarOrderManager delFromBTUserList exec, socket_id:[%s], uid:[%s], \nlist:%s" % (socket_id,uid, tmpList))
 
    #---是否在I台队列
    def isInTUserList(self, tmpUser):
        tmpAwait = self.get_T_user_order(tmpUser)
        return tmpAwait > 0
        
 
    def pushTListToSomebody(self, tmpOwnerUser):
        '''发T台异性队列给某人'''
        if tmpOwnerUser is None:
            return
        
        tmpCmd = "bar_push_t"
        tmpTUserUID = BarOrderManager.s_bar_T_boy_current_uid            #酒吧-T台排队列表 男 UID
        tmpTUserList = BarOrderManager.s_list_bar_T_boy
        if tmpOwnerUser.getSex() == 1:
            tmpTUserUID = BarOrderManager.s_bar_T_girl_current_uid       #酒吧-T台排队列表 女 uid 
            tmpTUserList = BarOrderManager.s_list_bar_T_girl
            
        tmpSendMsgUtil = util.SendMsgUtil(None)  #消息发送器
        tmpTUserLength = len(tmpTUserList) #T台列表长度

        tmpSendMsgUtil.update_item("uid", tmpTUserUID)       #当前T台显示的玩家ID
        tmpSendMsgUtil.update_item("count", tmpTUserLength)  #T台排队人数  
        tmpSendMsgUtil.add_item("single_count", self.getTotalSingleCount())  #单身总数
        tmpSendMsgUtil.add_item("double_count", self.getTotalDoubleCount())  #房间总数 
        	
        tmpInfo = [] 
        tmpUser = UserManager.get_user_by_uid(tmpTUserUID)
        if tmpUser:
            tmpItems = self.getUserInfoToClient(tmpUser)
            tmpInfo.append(tmpItems)
                
        tmpSendMsgUtil.update_item("single", tmpInfo) 
        tmpSendMsgUtil.update_item("await", self.get_T_user_order(tmpOwnerUser)) #我当前排队位置 0:表示没在T台排队 
        tmpSendMsgUtil.send(cmd=tmpCmd, request=tmpOwnerUser.getRequest())
                
				
    def _pushTList(self, tmpCmd, tmpSingleList, tmpTUserList):
        '''单身队列， T台异性队列'''
        tmpSendMsgUtil = util.SendMsgUtil(None)  #消息发送器
        
        tmpSendTo = 0
        tmpTUserLength = len(tmpTUserList) #T台列表长度
        tmpFirstUID = 0
        if tmpTUserLength > 0:
            tmpFirstUID = tmpTUserList[0]
        tmpSendMsgUtil.update_item("uid", tmpFirstUID)       #当前T台显示的玩家ID
        tmpSendMsgUtil.update_item("count", tmpTUserLength)  #T台排队人数  
        tmpSendMsgUtil.add_item("single_count", self.getTotalSingleCount())  #单身总数
        tmpSendMsgUtil.add_item("double_count", self.getTotalDoubleCount())  #房间总数 
    		
        tmpInfo = []
        tmpShowCount = const.Config_BarOrderTListShowUserCount()  #返回多少个T台用户信息给客户端
        tmpShowUserList = tmpTUserList[0:tmpShowCount]
        for uid in tmpShowUserList:
            tmpUser = UserManager.get_user_by_uid(uid)
            if tmpUser:
                tmpItems = self.getUserInfoToClient(tmpUser)
                tmpInfo.append(tmpItems)
        tmpSendMsgUtil.update_item("single", tmpInfo)
        
        for uid in tmpSingleList:    #-往所有在线用户push T台信息
            tmpUser = UserManager.get_user_by_uid(uid)
            if tmpUser and tmpUser.isUserBarStateSingle(): #用户在线, 且单身
                tmpSendTo += 1
                tmpSendMsgUtil.update_item("await", self.get_T_user_order(tmpUser)) #我当前排队位置 0:表示没在T台排队 
                tmpSendMsgUtil.send(cmd=tmpCmd, request=tmpUser.m_request)
        
        return  tmpSendTo #返回已发数量
   
    def _timerTListFunc(self):
        '''T台队列定时器处理函数'''
        log.print_debug(logger, "BarOrderManager _timerTListFunc exec")
        tmpCmd = "bar_push_t"                    #T台队列(Push)
        
        tempSingleList_girl = BarOrderManager.s_list_bar_single_girl     #酒吧-单身女 UID
        tempTUserList_boy = BarOrderManager.s_list_bar_T_boy            #酒吧-T台排队列表 男 UID
        tmpTotalGirl = len(tempSingleList_girl)   
        tmpSendToGirl = self._pushTList(tmpCmd, tempSingleList_girl, tempTUserList_boy)
                
        tempSingleList_boy = BarOrderManager.s_list_bar_single_boy      #酒吧-单身 男 UID
        tempTUserList_girl = BarOrderManager.s_list_bar_T_girl           #酒吧-T台排队列表 女 uid
        tmpTotalBoy = len(tempSingleList_boy)
        tmpSendToBoy = self._pushTList(tmpCmd, tempSingleList_boy, tempTUserList_girl)
        
        self._delTListFunc(tempTUserList_boy, 1)   #从T台队列删除一个的用户
        self._delTListFunc(tempTUserList_girl, 0)  #从T台队列删除一个的用户
        
        log.print_debug(logger, "BarOrderManager _timerTListFunc exec, sendMsgToAll, cmd=[%s], totalBoy:[%s],SendToBoy:[%s]; totalGirl:[%s],SendToGirl:[%s]" 
                        % (tmpCmd, tmpTotalBoy, tmpSendToBoy, tmpTotalGirl, tmpSendToGirl))
 
    def _delTListFunc(self, tmpList, sex):
        '''从T台队列删除一个的用户''' 
        uid = 0
        if len(tmpList) > 0:
            uid = tmpList.pop(0)    #从T台队列删除一个
        if sex == 0:
            self._delPropPrivilegeBrooch(BarOrderManager.s_bar_T_girl_current_uid)#删除 T台胸花
            BarOrderManager.s_bar_T_girl_current_uid = uid
        else:
            self._delPropPrivilegeBrooch(BarOrderManager.s_bar_T_boy_current_uid) #删除 T台胸花
            BarOrderManager.s_bar_T_boy_current_uid = uid
        
    def _delPropPrivilegeBrooch(self, tmpUID):
        '''删除 T台胸花'''
        if tmpUID < 1:
            return
        tmpUser = UserManager.get_user_by_uid(tmpUID)
        if tmpUser:
            tmpUser.delUserInfoPropPrivilegeBrooch() #删除 T台胸花到 "正在使用的的特权道具列表"
 
    #---开启T台队列
    def startTimerTList(self):
        self.stopTimerTList()
        mstime = const.Config_BarOrderTListTime()    #酒吧名人堂多少秒push一次T台队列
        BarOrderManager.s_timer_id_t_list = util.TimerManager.instance().add_timer(self._timerTListFunc, mstime, -1)  
        log.print_debug(logger, "BarOrderManager startTimerTList, timer_id:[%s] " % BarOrderManager.s_timer_id_t_list)
    
    #----关闭T台队列
    def stopTimerTList(self):
        if BarOrderManager.s_timer_id_t_list > 0:
            log.print_debug(logger, "BarOrderManager stopTimerTList, timer_id:[%s] " % BarOrderManager.s_timer_id_t_list)
            util.TimerManager.instance().delete(BarOrderManager.s_timer_id_t_list)
            BarOrderManager.s_timer_id_t_list = 0
   
    
    #----后冠队列-------------------------------------------
    def getKingUserList(self, sex):
        if sex == 1:    #性别(0女 1男)
            return BarOrderManager.s_list_bar_king_boy
        else:
            return BarOrderManager.s_list_bar_king_girl 
    
    #----插入后冠队列
    def insertKingList(self, tmpUser):
        if tmpUser:
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID()
                
            tmpList = self.getKingUserList(tmpUser.getSex())
            util.inserList(tmpList, uid)
            
            log.print_debug(logger, "BarOrderManager insertKingList exec, socket_id:[%s], uid:[%s], \nlist:%s" % (socket_id,uid, tmpList))
    
    #---从后冠队列删除
    def delFromKingList(self, tmpUser):
        if tmpUser:
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID()

            tmpList = self.getKingUserList(tmpUser.getSex())         
            util.deleteFromList(tmpList, uid)
            
            log.print_debug(logger, "BarOrderManager delFromKingList exec, socket_id:[%s], uid:[%s], \nlist:%s" % (socket_id,uid, tmpList))
 
    
    #--------------------------------------------------------
    def getSingleUserList(self, sex):
        if sex == 1:    #性别(0女 1男)
            return BarOrderManager.s_list_bar_single_boy
        else:
            return BarOrderManager.s_list_bar_single_girl 

    def getMapProvinceSingleUser(self, sex):
        if sex == 1:    #性别(0女 1男)
            return BarOrderManager.s_map_user_by_province_single_boy
        else:
            return BarOrderManager.s_map_user_by_province_single_girl 

    def getSingleUserListExt(self, tmpUser, tmpCount):
        '''获取酒吧单身异性者, 优先获取同城'''
        if not tmpUser:
            return []
        tempSingleInfoList = []
        tmpSelectUIDListInMap = []   #已经选择的用户UID
        ownerUID = tmpUser.getUID()
        
        tmpBarManager = BarOrderManager.instance()  #酒吧名人堂管理对象 
        #---从按省排列的队列中获取单身者
        tmpMap = self.getMapProvinceSingleUser(tmpUser.getDiffentSex())
        tmpList = tmpMap.get(tmpUser.getProvince())
        if tmpList: 
            tmpRandList = util.getRandomFromList(tmpList, tmpCount)  #随机获取队列
            for uid in tmpRandList:
                tmpRandUser = UserManager.get_user_by_uid(uid)
                if tmpRandUser is None:
                    continue
                util.inserList(tmpSelectUIDListInMap, uid)   #已选择的UID
                tmpItems = tmpBarManager.getUserInfoToClientSimple(tmpRandUser) #获取用户信息
                tempSingleInfoList.append(tmpItems)

                tmpRandUser.insertBarSeeMeList(ownerUID)            #--把 我的uid加入到对方的“看见我的人队列"       
                tmpUser.insertBarISeeList(tmpRandUser.getUID())     #--把对方的uid加入到我的“我看见的人队列"  
    
        tmpLimitCount = tmpCount - len(tempSingleInfoList) #剩下需要获取的单身数量
        if tmpLimitCount == 0:
            return tempSingleInfoList
        
        #---从其它单身队列获取
        tmpList = self.getSingleUserList(tmpUser.getDiffentSex())
        tmpRandList = util.getRandomFromList(tmpList, tmpLimitCount)  #随机获取队列
        for uid in tmpRandList:
            if uid in tmpSelectUIDListInMap:#排除已选择的用户
                continue
            tmpRandUser = UserManager.get_user_by_uid(uid)
            if tmpRandUser is None:
                continue
            tmpItems = tmpBarManager.getUserInfoToClientSimple(tmpRandUser) #获取用户信息
            tempSingleInfoList.append(tmpItems)
            
            tmpRandUser.insertBarSeeMeList(ownerUID)            #--把 我的uid加入到对方的“看见我的人队列"       
            tmpUser.insertBarISeeList(tmpRandUser.getUID())     #--把对方的uid加入到我的“我看见的人队列" 
            
        return tempSingleInfoList
                    
    
    #----获取普通约会的房间map
    def getDoubleUserMap(self):
        tmpMap = {}
        for room_id, room in BarOrderManager.s_map_bar_room.items():
            #---约会房间状态 0:普通约会            #---房间打搅状态   #0: 默认, 1:使用了防打扰牌道具, 2:使用了隐形符  #--已续杯
            #if room and room.getRoomState() == 0 and room.getRoomStateNobother() in (0,1) and room.m_addtime_info.isAddtime():
            #    tmpMap[room_id] = room
            tmpMap[room_id] = room
        return tmpMap
    
    #----发送用户A的状态变化通知在“看见我的用户列表"的所有人
    def pushUserBarState(self, userObj):
        if userObj is None:
            return None
        
        tmpBarManager = BarOrderManager.instance()  #酒吧名人堂管理对象 
        tmpSendMsgUtil = util.SendMsgUtil(None)     #消息发送器
        tmpSendMsgUtil.add_item("uid", userObj.getUID())
        tmpSendMsgUtil.add_item("nickname", userObj.getNickname())
        
        tmpSendMsgUtil.add_item("current_place", userObj.getCurrentPlace())  #当前所在模块
        tmpSendMsgUtil.add_item("bar_state", userObj.getUserBarState())      #酒吧状态 0:单身, 1:约会中, 2:PK中  (-1:退出酒吧/名人堂)
        tmpSendMsgUtil.add_item("room_id", userObj.getRoomID())  #约会房间ID
        
        #---房间人员信息
        tmpRoomInfo = []
        room_id = userObj.getRoomID(); #房间ID
        tmpRoom = tmpBarManager.s_map_bar_room.get(room_id);#房间对象    
        if tmpRoom:
            #--获取房间的状态
            tmpSendMsgUtil.add_item("room_state", tmpRoom.getRoomState())    #约会房间状态 0:普通约会  1:PK中
            tmpSendMsgUtil.add_item("state_nobother", tmpRoom.getRoomStateNobother())  #房间打搅状态   #0: 默认, 1:使用了防打扰牌道具, 2:使用了隐形符
            tmpSendMsgUtil.add_item("state_addtime", tmpRoom.m_addtime_info.getAddTimeState()) #房间续杯状态, 0:未续杯  1:已续杯
            tmpSendMsgUtil.add_item("uid_pk", tmpRoom.getPKUID())   #房间PK状态, 返回小三UID, 否则为0
            
            #--房间存在， 则获取房间人员信息
            userObjs = tmpRoom.getRoomUserObjList()
            for v in userObjs:
                tmpItems = tmpBarManager.getUserInfoToClientSimple(v) #用户信息
                tmpRoomInfo.append(tmpItems)        
        tmpSendMsgUtil.add_item("room", tmpRoomInfo)  #房间人员信息
        
        #---给看见我的用户push消息
        tmpMsg = tmpSendMsgUtil.getEncodeContent() #-编码        
        tmpUserNum = 0
        tmpSendNum = 0
        
        for uid in userObj.getBarSeeMeList():   #看见我的用户列表
            tmpUserNum += 1
            tmpUser = UserManager.get_user_by_uid(uid)        
            if tmpUser is None:                 #用户不存在, 则从 ”看见我的“ 删除
                userObj.delBarSeeMeList(uid)
                continue
            if tmpUser.isUserBarStateExit():    #用户不在酒吧, 则从 ”看见我的“ 删除
                userObj.delBarSeeMeList(uid)
                continue
            
            tmpSendNum += 1
            tmpSendMsgUtil.send(cmd="bar_push_user_state", request=tmpUser.getRequest(), msg=tmpMsg)
                 
        log.print_debug(logger, "pushUserBarState exec, socket_id:[%s], uid:[%s], SeeMeUserCount:[%s], sendCount:[%s]" 
             % (userObj.getSocketID(), userObj.getUID(), tmpUserNum, tmpSendNum))
    
    #----插入自动等待邂逅队列--------------------------------------
    def getBarAutoListBySex(self, sex):
        '''根据性别获取列表'''
        tmpAddrMap = BarOrderManager.s_map_user_by_province_auto_girl   #酒吧-单身随机邂逅等待列表女 {"省":[uid]} 
        tmpList = BarOrderManager.s_list_bar_auto_girl
        if sex == 1:
            tmpList = BarOrderManager.s_list_bar_auto_boy
            tmpAddrMap = BarOrderManager.s_map_user_by_province_auto_boy  #酒吧-单身随机邂逅等待列表男 {"省":[uid]}
        return (tmpList, tmpAddrMap)
        
    def insertBarAutoList(self, tmpUser):
        if tmpUser:
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID()
            
            tmpList, tmpAddrMap = self.getBarAutoListBySex(tmpUser.getSex())
            util.inserList(tmpList, uid)    #酒吧-随机邂逅等待列表
            
            #---插入按省排列的单身随机邂逅等待列表
            tmpProvince = tmpUser.getProvince()
            if tmpAddrMap.has_key(tmpProvince):
                tmpUIDList = tmpAddrMap.get(tmpProvince)
                if tmpUIDList is None:
                    tmpUIDList = []
                util.inserList(tmpUIDList, uid)
            else:
                tmpAddrMap[tmpProvince] = [uid]
            
            log.print_debug(logger, "BarOrderManager insertBarAutoList exec, socket_id:[%s], uid:[%s], \nlist:%s" % (socket_id,uid, tmpList))

    def getAutoUserInList(self, tmpList, tmp_set_my):
        '''从队列里获取交集最长的 用户'''
        tmpAotoUser = None
        tmpIntersectionLen = 0   #初始化交集的长度       
        #tmpUnionLen = 0;        #初始化并集的长度   
        tmpConfigInterLen = const.Config_Bar_auto_ask_InterLen()  #配置, 匹配有多少项相同特质 的异性
        
        for uid in tmpList:
            tmpUser = UserManager.get_user_by_uid(uid)
            if tmpUser is None or not tmpUser.isUserBarStateSingle(): #不在线 或 非单身状态, 则从自动队列删除
                util.deleteFromList(tmpList, uid)
                continue

            toAutoinfo = tmpUser.getAutoInfo()          #获取用户自动匹配信息
            tmp_set_other = set(toAutoinfo.values())       #set 
            
            tmpInterLen = len(tmp_set_my & tmp_set_other)  #交集长度
            if tmpInterLen >= tmpIntersectionLen:           #交集最长， 表示最匹配 
                tmpIntersectionLen = tmpInterLen
                tmpAotoUser = tmpUser
            if tmpInterLen >= tmpConfigInterLen:           #匹配有多少项相同特质 的异性
                break
                
#                    UnionLen = len(dict([(i,myAutoinfo[i]) for i in filter(myAutoinfo.has_key,toAutoinfo.keys()) if myAutoinfo[i]==toAutoinfo[i]]))#当前用户与被撮合用户的并集长度
#                    if UnionLen>tmpUnionLen:#如果并集后的长度最短，则这个用户就是最匹配的
#                        tmpAotoUser = tmpUser  

#                    UnionLen = len(dict(myAutoinfo,**toAutoinfo))#当前用户与被撮合用户的并集长度
#                    if UnionLen<tmpUnionLen:#如果并集后的长度最短，则这个用户就是最匹配的
#                        tmpAotoUser = tmpUser  
        return tmpAotoUser  
    
    #---从自动等待邂逅队列获取一个用户
    def getAutoUser(self, tmpOwnerUser):
        tmpAotoUser = None
        if tmpOwnerUser:
            tmpList, tmpAddrMap = self.getBarAutoListBySex(tmpOwnerUser.getDiffentSex())#获取异性列表
   
            tmpMyProvince = tmpOwnerUser.getProvince()
            myAutoinfo = tmpOwnerUser.getAutoInfo() #获取用户自动匹配信息
            tmp_set_my = set(myAutoinfo.values())   #set
            
            #--先从 省 map 里获取单身异性
            if tmpAddrMap.has_key(tmpMyProvince):
                tmpUIDList = tmpAddrMap.get(tmpMyProvince)
                if tmpUIDList:
                    tmpAotoUser = self.getAutoUserInList(tmpUIDList, tmp_set_my)
            
            #---获取不到同省的，则获取其它匹配条件的
            if not tmpAotoUser:
                tmpAotoUser = self.getAutoUserInList(tmpList, tmp_set_my)
            
        return tmpAotoUser
    
    #----从自动等待邂逅队列删除
    def delFromAutoList(self, tmpUser):
        if tmpUser:
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID()
          
            tmpList, tmpAddrMap = self.getBarAutoListBySex(tmpUser.getSex())
            util.deleteFromList(tmpList, uid)    #酒吧-自动等待邂逅列表
            
            #---按省排列的单身等待邂逅队列中删除
            tmpProvince = tmpUser.getProvince()
            if tmpAddrMap.has_key(tmpProvince):
                tmpUIDList = tmpAddrMap.get(tmpProvince)
                if tmpUIDList:
                    util.deleteFromList(tmpUIDList, uid) 
					
            log.print_debug(logger, "BarOrderManager delFromAutoList exec, socket_id:[%s], uid:[%s], \nlist:%s" % (socket_id,uid, tmpList))
    
 
    #----插入单身队列--------------------------------------
    def getBarSingleListBySex(self, sex):
        tmpAddrMap = BarOrderManager.s_map_user_by_province_single_girl    #酒吧-单身女 {"省":[uid]} 
        tmpList = BarOrderManager.s_list_bar_single_girl
        if sex == 1: #性别(0女 1男)
            tmpList = BarOrderManager.s_list_bar_single_boy
            tmpAddrMap = BarOrderManager.s_map_user_by_province_single_boy  #酒吧-单身男 {"省":[uid]}
        return tmpList, tmpAddrMap 
  
    def insertBarSingleList(self, tmpUser):
        if tmpUser:
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID()

            tmpList, tmpAddrMap = self.getBarSingleListBySex(tmpUser.getSex()) 
            util.inserList(tmpList, uid) #-插入单身队列
            
            #---插入按省排列的单身队列
            tmpProvince = tmpUser.getProvince()
            if tmpAddrMap.has_key(tmpProvince):
                tmpUIDList = tmpAddrMap.get(tmpProvince)
                if tmpUIDList is None:
                    tmpUIDList = []
                util.inserList(tmpUIDList, uid)
            else:
                tmpAddrMap[tmpProvince] = [uid]
            
            log.print_debug(logger, "BarOrderManager insertBarSingleList exec, socket_id:[%s], uid:[%s], \nlist:%s" % (socket_id,uid, tmpList))
     
    #---从单身队列删除
    def delFromBarSingleList(self, tmpUser):
        if tmpUser:
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID()
                
            tmpList, tmpAddrMap = self.getBarSingleListBySex(tmpUser.getSex())        
            util.deleteFromList(tmpList, uid)  #-单身队列删除
            
            #---按省排列的单身队列中删除
            tmpProvince = tmpUser.getProvince()
            if tmpAddrMap.has_key(tmpProvince):
                tmpUIDList = tmpAddrMap.get(tmpProvince)
                if tmpUIDList:
                    util.deleteFromList(tmpUIDList, uid) 
            
            log.print_debug(logger, "BarOrderManager delFromBarSingleList exec, socket_id:[%s], uid:[%s], \nlist:%s" % (socket_id,uid, tmpList))
       
    #---离开酒吧、名人堂,或者掉线时，如果在约会房间，则离开约会房间-------------------
    def _leveRoom(self, request, tmpA):
        import process_bar_order

        socket_id = request.socket_id
        if tmpA.isUserBarStateSingle(): #单身
            log.print_debug(logger, "BarOrderManager _leveRoom exec, socket_id:[%s], tmpA.isUserBarStateSingle()" % socket_id)  
            return
        
        room_id = tmpA.getRoomID(); #房间ID
        tmpRoom = BarOrderManager.s_map_bar_room.get(room_id);#房间对象    
        if tmpRoom is None:     #房间不存在
            log.print_debug(logger, "BarOrderManager _leveRoom exec, socket_id:[%s], tmpRoom:[%s] is None" % (socket_id, room_id))  
            return
        
        tmpRoom.stopAllTimer()  #关闭该房间所有定时器
        
        tmpAUID = tmpA.getUID()
        
        if not tmpRoom.isStatePK(): #普通约会(两人)
            log.print_debug(logger, "BarOrderManager _leveRoom exec, socket_id:[%s], not tmpRoom.isStatePK()" % socket_id)  
            tmpUserList = tmpRoom.getRoomUserObjList()
            process_bar_order._deleteRoomProcess(tmpRoom, tmpUserList[0], tmpUserList[1], "offline", tmpAUID) #掉线
        
        else: #约会pk中            
            usersDict = tmpRoom.getRoomUserObjMapExt()  #获取房间所有人信息,返回字典 '''    
            tmpUserOnly = usersDict["only"]             #裁判者 
            tmpUserOther = usersDict["other"]           #原配
            tmpUserPK = usersDict["pk"]                 #PK者
            
            if tmpAUID == tmpUserOnly.getUID(): #退出者是裁判
                log.print_debug(logger, "BarOrderManager _leveRoom exec, socket_id:[%s], existUser is only" % socket_id)  
                #--踢出PK者
                process_bar_order._bar_send_pk_result(request, tmpRoom, tmpUserOther.getUID()) 
                #--关闭房间
                process_bar_order._deleteRoomProcess(tmpRoom, tmpUserOnly, tmpUserOther, "offline", tmpAUID) #掉线
            
            elif tmpAUID == tmpUserPK.getUID(): #退出者是PK者
                log.print_debug(logger, "BarOrderManager _leveRoom exec, socket_id:[%s], existUser is pk" % socket_id)
                process_bar_order._bar_send_pk_result(request, tmpRoom, tmpUserOther.getUID())
            else: #退出者是原配
                log.print_debug(logger, "BarOrderManager _leveRoom exec, socket_id:[%s], existUser is other" % socket_id)
                process_bar_order._bar_send_pk_result(request, tmpRoom, tmpUserPK.getUID()) 


    #---离开酒吧、名人堂,或者掉线
    def leaveBarOrder(self, request, tmpA, bClose=False):
        socket_id = request.socket_id
        log.print_debug(logger, "BarOrderManager leaveBarOrder exec, socket_id:[%s]" % socket_id)  
    
        if tmpA is None or tmpA.isUserBarStateExit():#不在酒吧或者名人堂
            log.print_debug(logger, "BarOrderManager leaveBarOrder exec, socket_id:[%s], tmpA is None or tmpA.isUserBarStateExit()" % socket_id)  
            return
        
        self._leveRoom(request, tmpA) #如果在约会房间，则离开约会房间
  
        self._leave(tmpA)                       #--从酒吧队列清除      
        tmpA.setCurrentPlace("default")         #--设置用户当前模块为默认 
        self.pushUserBarState(tmpA)             #--通知所有看见A的人, A状态变化(离开酒吧名人堂)
        
        if bClose:  #掉线状态
            self.delFromBTUserList(tmpA)        #从T台队列删除
            self.delFromKingList(tmpA)          #--掉线, 则从"后冠"排队队列删除
       
        #--清空A的"我看见的人" "看见我的人"列表
        tmpA.clearBarSeeMeList()
        tmpA.clearBarISeeList()
    
    
    #---获取名人堂排名
    def getOrder(self, tmpUser):
        tmpOrder = 1
        if tmpUser:
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID()
           
            tmpList = BarOrderManager.s_map_order_girl
            if tmpUser.getSex() == 1:
                tmpList = BarOrderManager.s_map_order_boy  

            if tmpList.has_key(uid):
                tmpOrder = tmpList.get(uid)
            else:
                tmpOrder = len(tmpList) + 1
            log.print_debug(logger, "getOrder exec, socket_id:[%s], uid:[%s], order:[%s]" % (socket_id,uid, tmpOrder))
        return tmpOrder

    #---名人堂排名
    def sort(self):
        tmpListBarSingle = BarOrderManager.s_list_bar_single_boy
        tmpMapUser = BarOrderManager.s_map_order_boy
        tmpMapByOrder = BarOrderManager.s_map_order_boy_by_order
        tmpListKing = BarOrderManager.s_list_bar_king_boy
        self._sortExt(tmpListBarSingle, tmpMapUser, tmpMapByOrder, tmpListKing)
        
        tmpListBarSingle = BarOrderManager.s_list_bar_single_girl
        tmpMapUser = BarOrderManager.s_map_order_girl
        tmpMapByOrder = BarOrderManager.s_map_order_girl_by_order
        tmpListKing = BarOrderManager.s_list_bar_king_girl
        self._sortExt(tmpListBarSingle, tmpMapUser, tmpMapByOrder, tmpListKing)

    def _sortExt(self, tmpListBarSingle, tmpMapUser, tmpMapByOrder, tmpListKing):
        '''计算排名(包括后冠的用户)'''
        tmpTimeBegin = time.time() 

        #---copy
        tmpSortMap = {}
        tmpMapUser.clear() #清空
        tmpMapByOrder.clear() #清空
        
        #---先给后冠排序        
        for uid in tmpListKing:
            tmpUser = UserManager.get_user_by_uid(uid)
            if tmpUser:
                #--判断该用户后冠是否有效, 无效则从队列删除
                from props_manager import PropManager
                tmpProps = PropManager.instance().isUsingPropKing(tmpUser)
                if not tmpProps:                    
                    self.delFromKingList(tmpUser)
                    continue
                #--后冠有效, 则获取数值总数
                tmpSortMap[uid] = tmpUser.getOrderValue()         
        #---sort
        tmpTupleList = (sorted(tmpSortMap.items(), key=lambda v: v[1], reverse=True)) #根据数值排名, 数值从大到小
                
        #---copy
        tmpOrder = 0
        for v in tmpTupleList:
            tmpU = {"type":"single"}		   #"default":一页多人,  "single":一页一人
            tmpOrder += 1
            tmpMapUser[v[0]] = tmpOrder        #{uid:排名}
            tmpU["uid"] = v[0]
            tmpMapByOrder[tmpOrder] = tmpU     #{排名: {type, uid}}
        

        #--单身队列排序, 把有皇冠的人从单身队列删除
        tmpSortMap = {}
        tmpList = tmpListBarSingle[:]
        for uid in tmpListKing:
            util.deleteFromList(tmpList, uid)
        
        for uid in tmpList:
            tmpUser = UserManager.get_user_by_uid(uid)
            if tmpUser:
                tmpSortMap[uid] = tmpUser.getOrderValue() #获取数值总数        
        #---sort
        tmpTupleList = ()
        tmpTupleList = (sorted(tmpSortMap.items(), key=lambda v: v[1], reverse=True)) #根据数值排名,数值从大到小
        
        #---copy
        for v in tmpTupleList:
            tmpU = {"type":"default"}          #"default":一页多人,  "single":一页一人
            tmpOrder += 1
            tmpMapUser[v[0]] = tmpOrder        #{uid:排名}
            tmpU["uid"] = v[0]
            tmpMapByOrder[tmpOrder] = tmpU     #{排名: {type, uid}}
            
        tmpTimeEnd = time.time()
        tmpTimeInterval = tmpTimeEnd - tmpTimeBegin
        log.print_debug(logger, "count bar order: _sortExt exec, usetime:[%s], size:[%s]" %(tmpTimeInterval, len(tmpMapUser)))

    def _timerSortFunc(self):
        '''排序定时器处理函数'''
        log.print_debug(logger, "BarOrderManager _timerSortFunc exec")

        self.sort() #排序
        
        tmpSendMsgUtil = util.SendMsgUtil(None)  #消息发送器        
        tmpCmd = "push_order_change"             #用户排名改变(Push)
        
        tempMap = BarOrderManager.s_map_order_boy_by_order     #名人堂-排名列表 男 {排名: {type, uid}}
        tmpTotalBoy = len(tempMap)   
        tmpSendToBoy = 0 
        for index, obj in tempMap.items(): #-往所有在线用户push排名(男)
            uid = obj.get("uid")
            tmpUser = UserManager.get_user_by_uid(uid)
            if tmpUser:
                tmpSendToBoy += 1
                tmpSendMsgUtil.update_item("uid", uid)
                tmpSendMsgUtil.update_item("order", index)
                tmpSendMsgUtil.update_item("type", obj.get("type"))
                tmpSendMsgUtil.send(cmd=tmpCmd, request=tmpUser.m_request)
                
        tempMap = BarOrderManager.s_map_order_girl_by_order    #名人堂-排名列表 女{排名: {type, uid}}
        tmpTotalGirl = len(tempMap)
        tmpSendToGirl = 0
        for index, obj in tempMap.items():#-往所有在线用户push排名(女)
            uid = obj.get("uid")
            tmpUser = UserManager.get_user_by_uid(uid)
            if tmpUser:
                tmpSendToGirl += 1
                tmpSendMsgUtil.update_item("uid", uid)
                tmpSendMsgUtil.update_item("order", index)
                tmpSendMsgUtil.update_item("type", obj.get("type"))
                tmpSendMsgUtil.send(cmd=tmpCmd, request=tmpUser.m_request)
        
        log.print_debug(logger, "BarOrderManager _timerSortFunc exec, sendMsgToAll, cmd=[%s], totalBoy:[%s],SendToBoy:[%s]; totalGirl:[%s],SendToGirl:[%s]" 
                        % (tmpCmd, tmpTotalBoy, tmpSendToBoy, tmpTotalGirl, tmpSendToGirl))
        

    #----开启排序定时器
    def startTimerSort(self):
        self.stopTimerSort()
        mstime = const.Config_BarOrderSortTime()    #酒吧名人堂多少秒排序并push
        BarOrderManager.s_timer_id_sort = util.TimerManager.instance().add_timer(self._timerSortFunc, mstime, -1)  
        log.print_debug(logger, "BarOrderManager startTimerSort, timer_id:[%s] " % BarOrderManager.s_timer_id_sort)
    
    #----关闭排序定时器
    def stopTimerSort(self):
        if BarOrderManager.s_timer_id_sort > 0:
            log.print_debug(logger, "BarOrderManager stopTimerSort, timer_id:[%s] " % BarOrderManager.s_timer_id_sort)
            util.TimerManager.instance().delete(BarOrderManager.s_timer_id_sort)
            BarOrderManager.s_timer_id_sort = 0


    #--------以下为约会房间管理-----
    def addRoom(self, sendAskObj, otherObj):
        '''新建立房间, 传入请求者, 被搭讪者对象'''
        if sendAskObj is None or otherObj is None:
            log.print_warning(logger, "BarOrderManager add_room fail, parms UserObj is None")
            return None
        
        send_ask_uid = sendAskObj.getUID()
        other_uid = otherObj.getUID()    
        
        if send_ask_uid == other_uid:
            log.print_warning(logger, "BarOrderManager add_room fail: ask_uid[%s] == otherUid[%s]" 
                              %(send_ask_uid, other_uid))
            return None
            
        BarOrderManager.s_room_index += 1

        tmpRroomID = BarOrderManager.s_room_index               #房间ID               
        tmpRoom = Room(tmpRroomID, send_ask_uid)                #新房间        
        tmpRoom.enter(sendAskObj)   #用户进入房间
        tmpRoom.enter(otherObj)     #用户进入房间
                    
        BarOrderManager.s_map_bar_room[tmpRroomID] = tmpRoom    #保存到房间列表        
        log.print_debug(logger, "BarOrderManager add_room success, roomID:[%s], ask_uid:[%s], otherUid:[%s]" 
                        %(tmpRroomID, send_ask_uid, other_uid)) 
        return tmpRoom
    
    def getRoom(self, room_id):
        return BarOrderManager.s_map_bar_room.get(room_id)
    
    #----获取房间对象, 对象不存在, 则发错误信息通知
    def getRoomExt(self, cmd, tmpSendMsgUtil, socket_id, room_id):
        '''参数:(命令字, 发送器，socket_id, room_id)'''
        tmpObj = BarOrderManager.s_map_bar_room.get(room_id);#房间对象    
        if tmpObj is None:
            log.print_warning(logger, "getRoomExt exec, sockID:[%s], room:[%s] is null" % (socket_id, room_id)) 
            tmpSendMsgUtil.update_res("room_is_null")     
            tmpSendMsgUtil.send(cmd) 
        return tmpObj
    
    def removeRoom(self, roomObj):
        if roomObj:
            room_id = roomObj.m_room_id
            self.removeRoomByRoomID(room_id)
    
    def removeRoomByRoomID(self, room_id):
        if BarOrderManager.s_map_bar_room.has_key(room_id):
            log.print_debug(logger, "removeRoomByRoomID exec, roomID:[%s]" % room_id)
            BarOrderManager.s_map_bar_room.pop(room_id) 


